In computer science, string interning is a method of storing only one copy of each distinct string value, which must be Immutable object. Interning strings makes some string processing tasks more time-efficient or space-efficient at the cost of using more time when the string is created or interned. The distinct values are stored in a string intern pool.
The one copy of each string is called its intern and is typically looked up by a method of the string class, for example String.intern() in Java. All compile time constant strings in Java are automatically interned using this method.
String interning is supported by some modern object-oriented programming languages, including Java, Python, PHP (since 5.4), Lua and .NET languages. Lisp, Scheme, Julia, Ruby and Smalltalk are among the languages with a symbol type that are functionally similar to interned strings. The library of the Standard ML of New Jersey contains an atom type with a similar purpose. Objective-C selectors, which are mainly used as method names, are interned strings.
Objects other than strings can be interned. For example, in Java, when primitive values are boxed into a wrapper object, certain values (any boolean, any byte, any char from 0 to 127, and any short or int between −128 and 127) are interned, and any two boxing conversions of one of these values are guaranteed to result in the same object.
Modern Lisp dialects typically distinguish symbols from strings; interning a given string returns an existing symbol or creates a new one, whose name is that string. Symbols often have additional properties that strings do not such as storage for associated values, or namespacing. The distinction is also useful to prevent accidentally comparing an interned string with a not-necessarily-interned string, which could lead to intermittent failures depending on usage patterns.
String interning also reduces memory usage if there are many instances of the same string value; for instance, it is read from a computer network or from Computer storage. Such strings may include magic numbers or network protocol information. For example, XML parsers may intern names of tags and attributes to save memory. Network transfer of objects over Java RMI serialization object streams can transfer strings that are interned more efficiently, as the String object's handle is used in place of duplicate objects upon serialization.
Contention can also be reduced by partitioning the string space into multiple pools, which can be synchronized independently of one another.
|
|